import React, { useEffect, useRef, forwardRef } from "react";
import "quill/dist/quill.snow.css";

const QuillEditor = forwardRef(({ value, onChange, ...props }, ref) => {
  const editorRef = useRef(null);
  const quillInstance = useRef(null);

  useEffect(() => {
    if (editorRef.current && !quillInstance.current) {
      import("quill").then((Quill) => {
        quillInstance.current = new Quill.default(editorRef.current, {
          theme: "snow",
          modules: {
            toolbar: [
              ["bold", "italic", "underline", "strike"],
              ["blockquote", "code-block"],
              [{ header: 1 }, { header: 2 }],
              [{ list: "ordered" }],
              [{ script: "sub" }, { script: "super" }],
              [{ indent: "-1" }, { indent: "+1" }],
              [{ direction: "rtl" }],
              [{ size: ["small", false, "large", "huge"] }],
              [{ header: [1, 2, 3, 4, 5, 6, false] }],
              [{ color: [] }, { background: [] }],
              [{ font: [] }],
              [{ align: [] }],
              ["clean"],
              ["link", "image", "video"],
            ],
          },
          formats: [
            "header",
            "font",
            "size",
            "bold",
            "italic",
            "underline",
            "strike",
            "blockquote",
            "list",
            "indent",
            "link",
            "image",
            "video",
          ],
          placeholder: "请输入内容...",
        });

        if (value) {
          quillInstance.current.clipboard.dangerouslyPasteHTML(value);
        }

        quillInstance.current.on("text-change", () => {
          const html = editorRef.current.querySelector(".ql-editor").innerHTML;
          if (onChange) {
            onChange(html);
          }
        });
      });
    }
  }, []);

  // 监听外部值变化
  useEffect(() => {
    if (
      quillInstance.current &&
      value !== quillInstance.current.root.innerHTML
    ) {
      quillInstance.current.clipboard.dangerouslyPasteHTML(value || "");
    }
  }, [value]);

  // 暴露编辑器实例给父组件
  React.useImperativeHandle(ref, () => ({
    getEditor: () => quillInstance.current,
    getContent: () => editorRef.current?.querySelector(".ql-editor").innerHTML,
    setContent: (content) => {
      if (quillInstance.current) {
        quillInstance.current.clipboard.dangerouslyPasteHTML(content);
      }
    },
  }));

  return <div ref={editorRef} {...props} />;
});

export default QuillEditor;
